package com.cherrypt.api.core.aspect;

import com.cherrypt.api.common.enums.LogEnum;
import com.cherrypt.api.common.exception.TipException;
import com.cherrypt.api.core.util.IPUtils;
import com.cherrypt.api.core.service.LogService;
import com.cherrypt.api.core.util.JwtUtils;
import com.cherrypt.api.core.util.LogUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author intent
 * @date 2019/7/23 20:37
 * @about <link href='http://zzyitj.xyz/'/>
 */
@Aspect
@Component
public class UserAspect {
    private static final Logger logger = LoggerFactory.getLogger(UserAspect.class);

    @Autowired
    private LogService logService;

    @Pointcut("execution(* com.cherrypt.api.core.controller.UserController.avatarUpload(..))")
    public void avatarUpload() {
    }


    @AfterReturning(value = "avatarUpload()", returning = "result")
    public void avatarUploadLog(JoinPoint joinPoint, ResponseEntity result) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            try {
                int uid = JwtUtils.getUserIdFromRequest(request);
                LogUtils.writeLog(logService, uid, LogEnum.AVATAR_UPLOAD, result.toString(), request);
            } catch (TipException e) {
                logger.error("上传头像时获取uid错误，ip: " + IPUtils.getIpAddr(request), e);
            }
        }
    }
}
